package com.budwk.app.sqfw.services.common.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.bo.PdfResourceSortBO;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.services.common.SqfwExcelPdfForAdminCommonService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplateExcelCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwV2.service.centuryCity.OldCareServiceStationExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community
 * @description: 生成Excel文件服务实现
 * @author: LJT
 * @create: 2024-01-24 16:07
 **/
@IocBean
@Slf4j
public class SqfwExcelPdfForAdminCommonServiceImpl extends SqfwTemplateExcelCommonService implements SqfwExcelPdfForAdminCommonService {

    @Inject
    SysUserService sysUserService;

    @Inject
    SqfwCustomForAdminCommonService sqfwCustomForAdminCommonService;

    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private OldCareServiceStationExcelService oldCareServiceStationExcelService;

    /**
     * 批量生成excel
     *
     * @param bean
     * @return
     */
    @Override
    public List<GenerateExcelUrlVO> generateExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = sqfwCustomForAdminCommonService.buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        return  oldCareServiceStationExcelService.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), bean.getFormSummaryNewIdList());
    }

    /**
     * 批量生成pdf
     *
     * @param bean
     * @return
     */
    @Override
    public GenerateWordAndPdfUrlVO generatePdf(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = sqfwCustomForAdminCommonService.buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new GenerateWordAndPdfUrlVO();
            }
        }
        List<SqfwSummaryPdfExcelCollForAdminDTO> summaryIdServiceList = new ArrayList<SqfwSummaryPdfExcelCollForAdminDTO>();
        for (String id : bean.getFormSummaryNewIdList()) {
            SqfwSummaryPdfExcelCollForAdminDTO sqfwSummaryPdfExcelCollForAdminDTO = new SqfwSummaryPdfExcelCollForAdminDTO();
            sqfwSummaryPdfExcelCollForAdminDTO.setSumId(id);
            sqfwSummaryPdfExcelCollForAdminDTO.setServiceType(bean.getType());
            summaryIdServiceList.add(sqfwSummaryPdfExcelCollForAdminDTO);
        }
        generateWordAndPdfUrlVO.setPdfUrl(generatePdfColl(summaryIdServiceList));
        return generateWordAndPdfUrlVO;
    }

    /**
     * 生成pdf合集
     * @param conditionList
     * @return
     */
    public String generatePdfColl(List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList) {

        // 目前pdf存储于两个地方，一个是安全排查、垃圾分类、入户调查等业务的pdf存储在工作流中的sqfw_complete_flow的resource中
        // 另外的 12345、八单一表、简报、日报、其他任务都是存储于fileReport这张表中。
        List<PdfResourceSortBO> pdfBoList = Lists.newArrayList();

        Set<String> flowTypeSet = Sets.newHashSet(SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName());
        Set<String> fileReportTypeSet = Sets.newHashSet("其他");

        Map<String, SqfwSummaryPdfExcelCollForAdminDTO> fromFlowDTOMap = Maps.newHashMap();
        Map<String, SqfwSummaryPdfExcelCollForAdminDTO> fromFileReportMap = Maps.newHashMap();
        for (SqfwSummaryPdfExcelCollForAdminDTO sqfwSummaryPdfExcelCollForAdminDTO : conditionList) {
            String serviceType = sqfwSummaryPdfExcelCollForAdminDTO.getServiceType();
            if (flowTypeSet.contains(serviceType))
                fromFlowDTOMap.put(sqfwSummaryPdfExcelCollForAdminDTO.getSumId(), sqfwSummaryPdfExcelCollForAdminDTO);
            if (fileReportTypeSet.contains(serviceType))
                fromFileReportMap.put(sqfwSummaryPdfExcelCollForAdminDTO.getSumId(), sqfwSummaryPdfExcelCollForAdminDTO);
        }
        // 首先查询存储于sqfw_complete_flow中的数据
        if (fromFlowDTOMap.size() > 0) {
            Cnd cnd = Cnd.NEW();
            cnd.and("id", "in", fromFlowDTOMap.keySet());
            cnd.orderBy("fill_date", "asc");
            List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
            Map<String, Date> completeFlowIdDateMap = formSummaryList.stream()
                    .collect(Collectors.toMap(Sqfw_formSummary_new::getSqfwFlowId, Sqfw_formSummary_new::getFillDate));
            List<String> flowIdList = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
            Cnd flowCnd = Cnd.NEW();
            flowCnd.and("id", "in", flowIdList);
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.query(flowCnd);
            for (Sqfw_completeflow completeFlow : completeFlowList) {
                if (!completeFlow.getResourcePath().startsWith("/")) {
                    continue;
                }
                PdfResourceSortBO bo = new PdfResourceSortBO();
                Date fillDate = completeFlowIdDateMap.get(completeFlow.getId());
                bo.setSortDate(fillDate == null ? new Date() : fillDate);
                bo.setSqfwId(completeFlow.getSqfwId());
                bo.setPdfPath(completeFlow.getResourcePath());
                bo.setServiceType(completeFlow.getFileType());
                pdfBoList.add(bo);
            }
        }
        // 将这些文档按照时间先后顺序进行排序
        pdfBoList.sort(Comparator.comparing(PdfResourceSortBO::getSortDate));
        List<String> pdfPathList = pdfBoList.stream().map(PdfResourceSortBO::getPdfPath).collect(Collectors.toList());
        // 用于生成文件规则
        Set<String> serviceTypeTotalSet = conditionList.stream().map(SqfwSummaryPdfExcelCollForAdminDTO::getServiceType).collect(Collectors.toSet());
        String fileNameTemplate = "{}_{}";
        String fileNamePrefix = DownLoadFileNameEnum.OLD_CARE_SERVICE_PATROL_PDF.getName();
        String fileName = StrFormatter.format(fileNameTemplate, fileNamePrefix, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        String pdfUrl = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, fileName);
        if (Strings.isNotBlank(pdfUrl) && pdfUrl.startsWith("/")) {
            pdfUrl = NutzIocUtils.getOssPrefix() + pdfUrl;
        }
        return pdfUrl;
    }

    @Override
    protected void customerPopularBaseExcelParam(BaseExcelParamDTO baseExcelParam, String userId, List<String> sqfwIdList) {

    }

    @Override
    protected void customerPopularBaseExcelParamForAdmin(BaseExcelParamDTO baseExcelParam, String userId, List<String> formSummaryNewIdList) {
        Sys_user sysUser = sysUserService.fetch(userId);
        Map<String, Object> customerParamMap = new HashMap<String, Object>();
        customerParamMap.put("phone", sysUser.getMobile());
        baseExcelParam.setCustomerParamMap(customerParamMap);
    }

    @Override
    protected List<ExcelGeneratorConfig> getExcelCodeGeneratorConfig(List<ExcelCreateConfig> excelConfigList, BaseExcelParamDTO baseExcelParam) {
        return null;
    }

    @Override
    protected AbstractCustomerPdfCreateField parseParamData(String paramDataStr) {
        return null;
    }

    @Override
    protected String getSqfwFormSummaryType() {
        return null;
    }
}
